package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){
        //获取请求头
        String token = request.getHeader("Authorization");

        // 使用工具类 判断token 是否有效
        boolean b = JwtUtils.verifyToken(token);

        //如果token 失效 返回状态码401 拦截
        if (!b){
            response.setStatus(401);
            return false;
        }

        //如果token正常可用 放行

        //解析token 获取id和手机号 构造user对象 存入ThreadLocal；
        Claims claims = JwtUtils.getClaims(
                token);
        String mobile = (String) claims.get("mobile");
        Integer id = (Integer) claims.get("id");

        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        UserHolder.set(user);
        return true;
    }
}
